#coding= UTF-8

import sys
import json

from tornado.gen import coroutine, Return
from tornado.httpclient import HTTPError,AsyncHTTPClient

from core.scanner import ControllerManager
from core.ViewMaker import JsonView
from core.error import ControllerError
from services.xcx_auth import api

from pojo.json.JsonMsg import MsgMaker
from utils.jwter import JwtGenerator


@ControllerManager.register(r'/api/xcx/login', ('post'))
@coroutine
def xcx_login(request):
    app_key = request.get_argument('code')
    js_code = request.get_argument('js_code')
    if not app_key or not js_code:
        raise ControllerError('error_input',can_out_put=True)
    try:
        responce = yield AsyncHTTPClient().fetch(api.wx_login_request(js_code,app_key))
    except HTTPError:
        raise ControllerError('timeout')
    json_data = json.loads(responce.body)
    open_id = json_data['openid']
    user_id = api.xcx_login(open_id).uid
    jwt_code = JwtGenerator(user_id,24*3600*15).get()
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushAll({"token":jwt_code})
    raise Return(JsonView(msg_obj))  # 返回